<?php
class PasswordManagement extends CI_Controller {
	const tableName = "user";
	
	public function __construct()
	 {
	  	parent::__construct();
	  	date_default_timezone_set('PRC');

	 }
 
	public function index()  
	{	
		$this->password_management();
	}
	
	public function password_management()
	{
		$item[0]='我的订单';
		$url = base_url()."myCenterFolder/passwdManagement";
		$data['url'] = $url;
		$data['item']=$item;
		$data['left_tab'] = 'password_management';
		
		$this->load->view('myCenter/myCenter_home',$data);
		
	}
	
	// 修改密码 -> 验证原始密码
	function passwdValidation()
	{
		$this->load->library('form_validation');
		//form验证，为了实现Re-populating，需要验证，trim就可以了
		$this->form_validation->set_rules('oldPasswd', '原始密码', 'trim|required|min_length[1]|max_length[64]|callback_old_passwd_check');
		$this->form_validation->set_rules('newPasswd', '新密码', 'trim|required|min_length[1]|max_length[64]|matches[newPasswdConf]');
		$this->form_validation->set_rules('newPasswdConf', '重复密码', 'trim|required');
		
		$this->form_validation->set_message('required', '请正确填写 [%s]');
		$this->form_validation->set_message('max_length', '密码最大长度不能超过6');
		$this->form_validation->set_message('matches', '两次输入密码不一致');
		$this->form_validation->set_message('callback_old_passwd_check', '原始密码验证错误');
		
		if ($this->form_validation->run() == FALSE)
		{
			// 表单输入信息有误, 没有通过验证,返回到修改密码页
			$this->index();
			return;
		}else{
			// 通过了验证, 下面修改数据库
		}
		$data['oldPasswd'] = $_POST['oldPasswd'];	
		$data['newPasswd'] = $_POST['newPasswd'];
		$userId = $this->session->userdata('user_id');
        $data['userId']= $userId;
        $this->load->model('mycenter_model');
        $ret = $this->mycenter_model->changePassword($data);
        if($ret == TRUE){
        	// 修改密码成功
        }else{
        	// 修改密码失败
        }
        $this->index();
	}
	

	
	// 去数据库验证原始密码
	 public function old_passwd_check($str)
	 {
		  if ($str == '')
		  {
		  	   $this->form_validation->set_message('old_passwd_check', '%s不能为空');
			   return FALSE;
		  }
		  else
		  {
		  	   $userId = $this->session->userdata('user_id');
           	   $query = $this->db->get_where(self::tableName, array('id' => $userId,'password' => md5($str)));
		       if ($row = $query->row_array()){
		       		// 验证通过
					 return TRUE;
        		}else{
        			// 验证不通过
        			$this->form_validation->set_message('old_passwd_check', '%s验证不通过');
        			return FALSE;
        		}
		  	   return TRUE;
		  }
	 }
}
?>